/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.message;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.danlu.dlsms.model.pub.res.MessageExtension;
import com.danlu.dlsms.model.pub.res.MessageListResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.bus.MsgEvent;
import cn.com.dhc.danlu.model.bus.MsgEvent.MsgType;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.adapter.MyBaseAdapter;
import cn.com.dhc.danlu.widget.adapter.OrderMsgListAdapter;
import cn.com.dhc.danlu.widget.adapter.OtherMsgListAdapter;
import cn.com.dhc.mibd.eufw.widget.android.ptr.CustomListView;
import cn.com.dhc.mibd.eufw.widget.android.ptr.CustomPullToRefreshListView;
import cn.com.dhc.mibd.eufw.widget.android.ptr.PullToRefreshBase;
import cn.com.dhc.mibd.eufw.widget.android.ptr.PullToRefreshBase.Mode;
import cn.com.dhc.mibd.eufw.widget.android.ptr.PullToRefreshBase.OnRefreshListener2;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.pushmsg.MessageListRequest;
import cn.com.hd.mall.web.webservices.entity.request.pushmsg.SetMsgStatus;

import static cn.com.dhc.danlu.constant.MsgTypeConst.MsgTypeGroup;
import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-09-18 23:45<br/>
 * <p>
 * <p>
 * 订单消息列表和其他消息列表界面
 * </p>
 */
public class MessageListActivity extends BaseActivity implements OnRefreshListener2<CustomListView> {
    public static final String _TYPE_ADAPTER = "TypeAdapter";
    /**
     * 消息列表
     */
    private CustomPullToRefreshListView lstMessage;
    private LinearLayout llytBack;
    private TextView txtTitle;
    /**
     * from tag
     */
    private MsgType mType;
    private MyBaseAdapter mAdapter = null;

    private int mCurrentPage = 1;
    private boolean isFirstLoadSuc = true;
    private String showNoMoreTips;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_message_list);
        initViews();
        init();
        setThisMsgHasRead(); //最好放到请求回调成功的时候去执行
        getMessageList(true);
        EventBus.getDefault().register(this);
    }

    private void initViews() {
        lstMessage = (CustomPullToRefreshListView) findViewById(R.id.lstMessage);
        llytBack = (LinearLayout) findViewById(R.id.llytBack);
        txtTitle = (TextView) findViewById(R.id.txtTitle);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    private void init() {
        mType = (MsgType) getIntent().getSerializableExtra(_TYPE_ADAPTER);
        lstMessage.setMode(Mode.BOTH);
        lstMessage.setOnRefreshListener(this);
        // type == 0 订单消息  type == 1  其他消息
        if (mType == MsgType.ORDER_MSG) {
            mAdapter = new OrderMsgListAdapter(this);
            showNoMoreTips = getResources().getString(R.string.no_order_msg);
            txtTitle.setText("订单消息");
        } else {
            mAdapter = new OtherMsgListAdapter(this);
            showNoMoreTips = getResources().getString(R.string.no_other_msg);
            txtTitle.setText("其他消息");
        }
        lstMessage.getRefreshableView().setAdapter(mAdapter);

        //auto Refresh
        llytBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        lstMessage.setRefreshing(true);
    }

    private void setThisMsgHasRead() {
        SetMsgStatus request = new SetMsgStatus();
        request.receiverCompanyId = agent.getLoginUser().getCompanyId();
        request.receiverUserId = agent.getLoginUser().getUserId();
        request.type = mType == MsgType.ORDER_MSG ? MsgTypeGroup.PURCHASE_ORDER_MSG : MsgTypeGroup.MY_MSG + MsgTypeGroup.DANLU_ENVELOP_MSG;
        agent.getMsgApi().setMsgStatus(request)
                .compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>() {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {

                    }
                });
    }

    /**
     * 请求获取消息列表
     */
    private void getMessageList(final boolean isPullRefresh) {
        final MessageListRequest request = new MessageListRequest();
        request.channelId = CommonConst.CHANNEL_ID;
        request.receiverCompanyId = agent.getLoginUser().getCompanyId();
        request.receiverUserId = agent.getLoginUser().getUserId();
        request.type = mType == MsgType.ORDER_MSG ? MsgTypeGroup.PURCHASE_ORDER_MSG : MsgTypeGroup.MY_MSG + "," + MsgTypeGroup.DANLU_ENVELOP_MSG;
        request.defaultPaginationStrategy = false;
        // 考虑到未使用图层来切换视图 数据为空的情况下 上拉刷新 时 依然从第一页开始加载
        request.page = isPullRefresh || mAdapter.getCount() == 0 ? 1 : mCurrentPage;
        request.rows = 15;
        agent.getMsgApi().getMessageList(request)
                .compose(OperatorUtils.<MessageListResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<MessageListResponse>() {
                    @Override
                    protected void onSuccess(MessageListResponse res) {
                        List<MessageExtension> messageList = res.getMessageList();
                        if (null != messageList && !messageList.isEmpty()) {
                            if (isPullRefresh) {
                                mCurrentPage = 2;
                            } else {
                                mCurrentPage++;
                            }
                            if (isFirstLoadSuc) {
                                isFirstLoadSuc = false;
                                clearAllNotification();
                            }
                            bindData(messageList, isPullRefresh);
                        } else {
                            if (isPullRefresh) {
                                //下拉刷新
                                mCurrentPage = 1;
                                ToastUtil.getInstance().show("暂无" + (mType == MsgType.ORDER_MSG ? "订单消息" : "其他消息"));
                            } else {
                                ToastUtil.getInstance().show(showNoMoreTips);
                            }
                            lstMessage.onRefreshComplete();
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        lstMessage.onRefreshComplete();
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    protected void clearAllNotification() {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancelAll();
    }

    protected void bindData(List<MessageExtension> messageList, boolean isPullRefresh) {
        if (isPullRefresh) {
            mAdapter.refreshData(messageList);
        } else {
            mAdapter.appendData(messageList);
        }
        lstMessage.onRefreshComplete();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageArrived(MsgEvent event) {
        if (event.getEventFrom().equals(CommonConst.PushMsgFrom._FROM_PUSH_RECEIVER)) {
            lstMessage.setRefreshing(true);
            setThisMsgHasRead();
            getMessageList(true);
        }
    }

    /**
     * 当前界面处在消息列表界面，并且接受到最新的消息通知， 用户也点击了通知栏 重新刷新整个界面
     */
    @Override
    protected void onNewIntent(Intent intent) {
        // auto 下拉刷新
        lstMessage.setRefreshing(true);
        setThisMsgHasRead();
        getMessageList(false);
        super.onNewIntent(intent);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<CustomListView> refreshView) {
        getMessageList(true);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<CustomListView> refreshView) {
        getMessageList(false);
    }
}